package org.yzh.web.component.mybatis.handler;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.yzh.web.commons.JsonUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author lsj
 * @date 2021/1/13 14:47
 */
public abstract class AbstractObjectTypeHandler<T> extends BaseTypeHandler<T> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T t, JdbcType jdbcType)
        throws SQLException {
        ps.setString(i, JsonUtils.toJson(t));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName)
        throws SQLException {
        String data = rs.getString(columnName);
        return StringUtils.isBlank(data) ? null : JsonUtils.toObj((Class<T>) getRawType(), data);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String data = rs.getString(columnIndex);
        return StringUtils.isBlank(data) ? null : JsonUtils.toObj((Class<T>) getRawType(), data);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int i) throws SQLException {
        String data = cs.getString(i);
        return StringUtils.isBlank(data) ? null : JsonUtils.toObj((Class<T>) getRawType(), data);
    }
}
